package com.mlink.plugin.file;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import sun.misc.BASE64Encoder;

/**
 * 作者：宋鑫  2017-08-17 09:30
 * 2017-8-25日插件代码47.74.0.173:8088 172.16.1.141
 */
public class utils extends CordovaPlugin {
    private static final String TAG = "utils";
    public static String  url="http://cuteoa.unimlink.com:8080/CuteOA/mobile/appInterface/";
    public Context cxt;
    public SharedPreferences sp;
    public SharedPreferences.Editor ed;
    public String filePath, WPSDownLoadFile;
    ProgressDialog pd;
    //下载文件标记
    public static final int MY_DOWNLODFILE = 10001;
    //删除文件标记
    public static final int MY_DELECTFILE = 10002;
    //DownLoad方法的两个变量
    private String fileUrl, fileName;
    private CallbackContext mCallbackContext;

    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);
        cxt = cordova.getActivity();
        try {
            sp = cxt.getSharedPreferences("UserInfo", 1);
            ed = sp.edit();
		} catch (Exception e) {
		    String aa  = e.getMessage();
		   System.out.println(aa);
			// TODO: handle exception
			
		}

       
        filePath = cxt.getFilesDir().getAbsolutePath() + "/downloadfile/";
        WPSDownLoadFile = Environment.getExternalStorageDirectory().getPath() + "/ShangShiDownLoad";
    }

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        mCallbackContext = callbackContext;
        Log.d(TAG, "execute: " + args.toString() + "action::" + action);
        if (action.equals("setUserId")) {
            return setUserId(String.valueOf(args.get(0).toString()), callbackContext);
        }else if(action.equals("getChannlID")){
            return getChannlID(cxt, callbackContext);
        } else if (action.equals("getUserInfo")) {
            boolean isDelect = Boolean.valueOf(args.get(0).toString());
            Log.d(TAG, "execute: " + isDelect);
            return getUserInfo(isDelect, callbackContext);
        } else if (action.equals("previewFile")) {
            //调用wps预览附件
            fileUrl = String.valueOf(args.get(0));
            fileName = String.valueOf(args.get(1));
            //申请权限
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ContextCompat.checkSelfPermission(cxt,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED ||
                        ContextCompat.checkSelfPermission(cxt,
                                Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS)
                                != PackageManager.PERMISSION_GRANTED) {
                    cordova.requestPermissions(this, MY_DOWNLODFILE,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS});
                } else {
                    return DownLoad(cxt, fileUrl, fileName, callbackContext);
                }
            } else {
                return DownLoad(cxt, fileUrl, fileName, callbackContext);
            }
//            if (ContextCompat.checkSelfPermission(cxt,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                    != PackageManager.PERMISSION_GRANTED ||
//                    ContextCompat.checkSelfPermission(cxt,
//                    Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS)
//                    != PackageManager.PERMISSION_GRANTED) {
//                cordova.requestPermissions(this, MY_DOWNLODFILE,
//                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS});
//            } else {
//                return DownLoad(cxt, fileUrl, fileName, callbackContext);
//            }
        } else if (action.equals("deleteFile")) {
            //清除本地下载的附件
            return deleteFile(callbackContext);
        }
        return true;
    }

    public boolean getChannlID(Context cxt,CallbackContext call) {
        SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(cxt);
        String channlID = sp.getString("channelId", "null");
        JSONObject jsonObject = new JSONObject();
        if (channlID.equals("null")||channlID.equals("")) {
            try {
                jsonObject.put("code", "0");
                jsonObject.put("message", "本地未发现channelId");
                call.error(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }else{
            try {
                jsonObject.put("code", "1");
                jsonObject.put("message", channlID);
                call.success(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return true;
    }


    ////调用wps打开先下载附件
    public boolean DownLoad(final Context cxt, final String url, final String fileName, final CallbackContext callbackContext) {
        pd = ProgressDialog.show(cxt, "正在下载", "请稍后", true, false);
        Log.d(TAG, "DownLoad: ");
        if (!url.equals("null")&& url !=null && !fileName.equals("null") && !url.equals("") && !fileName.equals("")) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            client.newCall(request).enqueue(new Callback() {
                JSONObject obj = null;

                @Override
                public void onFailure(Call call, IOException e) {
                    Log.d(TAG, "onFailure:失败");
                    obj = new JSONObject();
                    try {
                        obj.put("code", "0");
                        obj.put("message", "下载失败");
                        callbackContext.error(obj.toString());
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }
                    pd.dismiss();
//                    callbackContext.error("下载失败");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.d(TAG, "onResponse: 成功");
                    //内存卡路径
                    final File paremFile = new File(WPSDownLoadFile);
                    //用文件目录打不开WPS
//                    final File paremFile = new File(cxt.getCacheDir()+"/downloadfile");
                    File downLoadFile = new File(WPSDownLoadFile, fileName);
                    if (!paremFile.exists()) {
                        paremFile.mkdir();
                    }
                    if (!downLoadFile.exists()) {
                        downLoadFile.createNewFile();
                    }
                    Log.d(TAG, "downLoadFile: " + downLoadFile.getAbsolutePath());
                    InputStream is = null;
                    byte[] buf = new byte[2048];
                    int len = 0;
                    FileOutputStream fos = null;
                    try {
                        long total = response.body().contentLength();
                        Log.e(TAG, "total------>" + total);
                        long current = 0;
                        is = response.body().byteStream();
                        fos = new FileOutputStream(downLoadFile);
                        while ((len = is.read(buf)) != -1) {
                            current += len;
                            fos.write(buf, 0, len);
                            Log.e(TAG, "current------>" + current);
                        }
                        fos.flush();
                        Log.d(TAG, "onResponse: 成功了");
                        pd.dismiss();
                        obj = new JSONObject();
                        if (isAppInstalled(cxt, "cn.wps.moffice_eng")) {
                            obj.put("code", "1");
                            obj.put("message", "下载成功，调用WPS打开");
                            callbackContext.success(obj.toString());
                        } else {
                            obj.put("code", "0");
                            obj.put("message", "下载成功，未安装WPS");
                            callbackContext.error(obj.toString());
                        }
                        openFile(downLoadFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                        obj = new JSONObject();
                        try {
                            obj.put("code", "0");
                            obj.put("message", "下载失败");
                            callbackContext.error(obj.toString());
                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                        Log.d(TAG, "onResponse:2 " + e.getMessage());
//                        callbackContext.error("下载失败");
                    } finally {
                        pd.dismiss();
                        try {
                            if (is != null) {
                                is.close();
                            }
                            if (fos != null) {
                                fos.close();
                            }
                        } catch (IOException e) {
                            Log.e(TAG, e.toString());
                        }
                    }
                }
            });
        }
        return true;
    }

    //判断是否安装了WPS
    private boolean isAppInstalled(Context context, String packagename) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packagename, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        if (packageInfo == null) {
            //System.out.println("没有安装");
            return false;
        } else {
            //System.out.println("已经安装");
            return true;
        }
    }


    public boolean openFile(File file) {
//        Log.d(TAG, "openFile: " + (cxt == null) + "path:" + file.getAbsolutePath());
//        Intent intent = new Intent();
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.setAction(Intent.ACTION_VIEW);
//        intent.setClassName("cn.wps.moffice_eng", "cn.wps.moffice.documentmanager.PreStartActivity2");
//        Uri uri = Uri.fromFile(file);
//        intent.setData(uri);
//        Log.d(TAG, "openFile: " + uri.toString());
//        try {
//            cxt.startActivity(intent);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return true;
     
         Intent intent = new Intent("android.intent.action.VIEW");  
         intent.addCategory("android.intent.category.DEFAULT");  
         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
       
         Uri apkUri = FileProvider.getUriForFile(cxt, "com.siicfm.oa.fileprovider", file);  
         intent.setDataAndType(apkUri, "text/plain");
         intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);  
         cxt.startActivity(intent);
         return true;  
    }

   
    //保存用户信息
    public boolean setUserId(String userId, CallbackContext callbackContext) {
        Log.d(TAG, "setUserId: " + userId);
        JSONObject json = new JSONObject();
        if (userId.equals("null")) {
            try {
                json.put("code", "0");
                json.put("message", "参数传入有误");
                callbackContext.error(json.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            if (userId != null && userId.equals("")) {
                ed.putString("userId", "");
                ed.putString("userMessage", "");
                ed.commit();
                try {
                    json.put("code", "1");
                    json.put("message", "本地userId已删除");
                    callbackContext.success(json.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (userId != null && !userId.equals("")) {
                ed.putString("userId", userId);
                ed.commit();
                try {
                    json.put("code", "1");
                    json.put("message", "userId保存成功");
                    callbackContext.success(json.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    //获取用户信息
    public boolean getUserInfo(boolean isDelect, CallbackContext call) {
        Log.d(TAG, "getUserInfo: " + isDelect);
        String userMessage = sp.getString("userMessage", "");
        JSONObject json = new JSONObject();
        if (isDelect) {
            if (userMessage.equals("")) {
                try {
                    json.put("code", "0");
                    json.put("message", "本地并无用户信息");
                    call.error(json.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                ed.putString("userMessage", "");
                ed.putString("userId", "");
                ed.commit();
                try {
                    json.put("code", "1");
                    json.put("message", "本地用户信息清除成功");
                    json.put("userInfo", new JSONObject(userMessage));
                    call.success(json.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } else {
            if (userMessage.equals("")) {
                try {
                    json.put("code", "0");
                    json.put("message", "本地并无用户信息");
                    call.error(json.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    json.put("code", "1");
                    json.put("message", "并未删除本地用户信息");

                    json.put("userInfo", new JSONObject(userMessage));
                    Log.d(TAG, "getUserInfo: " + json.toString());
                    call.success(json.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    //上传文件
    public static void testUploadFile(final String url, final String userId, final String fileName, final String filePath, final CallBack uploadCall) {
        new Thread() {
            @Override
            public void run() {
                //创建OkHttpClient对象
                OkHttpClient mOkHttpClient = new OkHttpClient();
                //将文件转换成base64
                String base64 = null;
                try {
                    base64 = encodeBase64File(filePath);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                base64 = base64.replaceAll("\r|\n", "");
                Log.d(TAG, "testUploadFile: " + userId);
                String json = "{\"REQUEST\":{\"HEAD\":{\"SERVICEID\":\"CLOUD_SUBMIT\"},\"BODY\":{\"userId\":\""
                        + userId + "\",\"fileName\":\"" + fileName + "\",\"filePath\":\"" + base64 + "\"}}}";
                Log.d(TAG, "run: " + json);
                RequestBody paramsBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json);
                Request request = new Request.Builder()
                        .url(url)
                        .header("SERVICEID", "CLOUD_SUBMIT")
                        .post(paramsBody)
                        .build();
                Call call = mOkHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d(TAG, "onFailure: " + e.getMessage());
                        Log.d(TAG, "onResponse: 上传失败");
                        uploadCall.setResponse("error", "upload");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String mResponse = response.body().string();
                        Log.d(TAG, "onResponse: 上传成功" + mResponse);
                        uploadCall.setResponse(mResponse, "upload");
                    }
                });
            }
        }.start();
    }

    //登录
    public static void Login(final CallBack ActivityCall, String userName, String passWord) {
        OkHttpClient client = new OkHttpClient();
        final String json = "{\"REQUEST\":{\"HEAD\":{\"SERVICEID\":\"USER_LOGIN\",\"APPVERSION\":\"VERSION\",\"SCRIPTVERSION\":\"VERSION\",\"DATE\":\"\",\"UUID\":\"\",\"USERID\":\"\",\"SIGN\":\"\",\"CHANNELID\":\"\",\"CURRENT_PAGE\":\"\",\"NEXT_PAGE\":\"\",\"DEVICETYPE\":\"\",\"DEVICEPIXELS\":\"\",\"OSVERSION\":\"\",\"OSTYPE\":\"\",\"TOKEN\":\"\",\"ACCESSCODE\":\"\"},\"BODY\":{\"loginName\":\"" + userName + "\",\"password\":\"" + passWord + "\",\"appId\":\"com.siic.oa\",\"deviceId\":\"com.siic.oa\"}}}";
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json);
        Request request = new Request.Builder()
                .url(url)
                .header("SERVICEID", "USER_LOGIN")
                .post(fileBody)
                .build();
        Call okCall = client.newCall(request);
        okCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ActivityCall.setResponse("error", "login");
                Log.d(TAG, "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseStr = response.body().string();
                ActivityCall.setResponse(responseStr, "login");
            }
        });
    }

    /* 将文件转成base64 字符串
     * @param path文件路径
	 */
    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return new BASE64Encoder().encode(buffer);
    }

    //清理缓存文件
    public boolean deleteFile(CallbackContext call) {
        JSONObject obj = new JSONObject();
        try {
            File dir = new File(WPSDownLoadFile);
            deleteDirWihtFile(dir);
            obj.put("code", "1");
            obj.put("message", "清理缓存成功");
            call.success(obj.toString());
        } catch (Exception e) {
            try {
                obj.put("code", "0");
                obj.put("message", "清理缓存失败");
                call.error(obj.toString());
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
        return true;
    }

    public static void deleteDirWihtFile(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete(); // 删除所有文件
            else if (file.isDirectory())
                deleteDirWihtFile(file); // 递规的方式删除文件夹
        }
        dir.delete();// 删除目录本身
    }

    @Override
    public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException {
        Log.d(TAG, "onRequestPermissionResult: " + grantResults[0]);
        if (grantResults[0] == 0) {
            switch (requestCode) {
                case MY_DOWNLODFILE:
                    DownLoad(cxt, fileUrl, fileName, mCallbackContext);
                    break;
                case MY_DELECTFILE:
                    deleteFile(mCallbackContext);
                    break;
            }
        } else {
        }
    }
}
